package com.example.dormitorysystem.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.dormitorysystem.common.rabbitmq.SendOrderMessage;
import com.example.dormitorysystem.entity.GroupsUser;
import com.example.dormitorysystem.entity.Orders;
import com.example.dormitorysystem.entity.pojo.OrderListsOutput;
import com.example.dormitorysystem.exception.CmsException;
import com.example.dormitorysystem.mapper.BuildingsMapper;
import com.example.dormitorysystem.mapper.GroupsMapper;
import com.example.dormitorysystem.mapper.GroupsUserMapper;
import com.example.dormitorysystem.mapper.OrdersMapper;
import com.example.dormitorysystem.service.OrdersService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import io.lettuce.core.output.StringListOutput;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.*;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author 吉吉王国组
 * @since 2022-11-26
 */
@Service
public class OrdersServiceImpl extends ServiceImpl<OrdersMapper, Orders> implements OrdersService {

    @Resource
    private SendOrderMessage sendOrderMessage;

    @Resource
    private GroupsMapper groupsMapper;

    @Resource
    private BuildingsMapper buildingsMapper;

    @Resource
    private OrdersMapper ordersMapper;

    @Resource
    private GroupsUserMapper groupsUserMapper;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    private static ArrayList<Integer> mBuildingId = new ArrayList<>();

    /**
     * 库存足够则消耗库存并生成订单
     * 后端只需要根据订单来修改数据库
     * @param input
     * @param request
     * @param response
     * @return
     */
    @Override
    public Map<String, Object> create(Map<String, Object> input, HttpServletRequest request, HttpServletResponse response) {
        Integer id = Integer.parseInt(request.getAttribute("uid").toString());
        int buildingId = (int) input.getOrDefault("building_id", -1);
        if (buildingId == -1) {
            throw new CmsException(402, "请输入楼id");
        }

        Orders orders = new Orders();
        System.out.println(input.get("group_id"));
        if (input.get("group_id") == null || input.get("group_id") == "") {
            // 未组队
            orders.setGroupId(0);
        } else {
            orders.setGroupId((Integer) input.get("group_id"));
        }

        // 偷个懒，验证楼id
        List<Integer> list = Arrays.asList(1, 2, 3, 4, 5);
        mBuildingId.addAll(list);
        if (!mBuildingId.contains(buildingId)) {
            throw new CmsException(403, "输入的楼id有误");
        }

        // 验证队伍id
        if(orders.getGroupId() != 0) {
            QueryWrapper<GroupsUser> groupsUserQueryWrapper = new QueryWrapper<>();
            groupsUserQueryWrapper.eq("uid", id);
            GroupsUser groupsUser = groupsUserMapper.selectOne(groupsUserQueryWrapper);
            if (groupsUser.getGroupId() != orders.getGroupId()) {
                throw new CmsException(404, "输入的队伍id有误");
            }
        }


        //看一下是几人宿舍
        QueryWrapper<GroupsUser> groupsUserQueryWrapperTarget = new QueryWrapper<>();
        groupsUserQueryWrapperTarget.eq("uid", id);
        Integer gender = groupsUserMapper.selectOne(groupsUserQueryWrapperTarget).getGender();
        Integer memberCount = groupsUserMapper.selectCount(groupsUserQueryWrapperTarget);

        //应该是先判断是否能够抢宿舍，再发送到后端，由后端实现数据库的修改
        if(gender == 0){
            if(memberCount == 6){
                //后面再优化，目前就直接用Hash的
                Long newCount = stringRedisTemplate.opsForValue().decrement(buildingId + "female_six_man_room");
                if(newCount < 0){
                    stringRedisTemplate.opsForValue().increment(buildingId + "female_six_man_room");
                    throw new CmsException(405, "该楼已无剩余六人间");
                }

            }else if (memberCount == 4){
                Long newCount = stringRedisTemplate.opsForValue().decrement(buildingId + "female_four_man_room");
                if(newCount < 0){
                    stringRedisTemplate.opsForValue().increment(buildingId + "female_four_man_room");
                    throw new CmsException(405, "该楼已无剩余四人间");
                }
            }
        }else if (gender == 1){
            if(memberCount == 6){
                Long newCount = stringRedisTemplate.opsForValue().decrement(buildingId + "male_six_man_room");
                if(newCount < 0){
                    stringRedisTemplate.opsForValue().increment(buildingId + "male_six_man_room");
                    throw new CmsException(405, "该楼已无剩余六人间");
                }
            }else if (memberCount == 4){
                Long newCount = stringRedisTemplate.opsForValue().decrement(buildingId + "male_four_man_room");
                if(newCount < 0){
                    stringRedisTemplate.opsForValue().increment(buildingId + "male_four_man_room");
                    throw new CmsException(405, "该楼已无剩余四人间");
                }
            }
        }

        orders.setUid(id);
        orders.setBuildingId(buildingId);
        orders.setSubmitTime(new Date());
        orders.setCreateTime(new Date());
        orders.setStatus(0);
        baseMapper.insert(orders);

        try {
            //到达这里，确定能够抢到一个宿舍，后端只需要直接分配即可
            sendOrderMessage.send(orders);
        } catch (Exception e) {
            throw new CmsException(400, "订单提交失败...");
        }
        HashMap<String, Object> stringObjectHashMap = new HashMap<>();
        stringObjectHashMap.put("order_id", orders.getId());
        return stringObjectHashMap;
    }

    @Override
    public List<OrderListsOutput> orderLists(HttpServletRequest request, HttpServletResponse response) {
        Integer id = Integer.parseInt(request.getAttribute("uid").toString());
        QueryWrapper<Orders> ordersQueryWrapper = new QueryWrapper<>();
        ordersQueryWrapper.eq("uid", id).orderByDesc("id");
        List<Orders> orders = baseMapper.selectList(ordersQueryWrapper);
        ArrayList<OrderListsOutput> orderListsOutputs = new ArrayList<>();
        for (Orders order : orders) {
            OrderListsOutput orderListsOutput = new OrderListsOutput();
            orderListsOutput.setOrder_id(order.getId());
            orderListsOutput.setGroup_name(groupsMapper.selectGroupName(order.getGroupId()));
            orderListsOutput.setBuilding_name(buildingsMapper.selectBuildingName(order.getBuildingId()));
            orderListsOutput.setSubmit_time(order.getSubmitTime());
            orderListsOutput.setResult_content(order.getResultContent());
            orderListsOutput.setStatus("未处理");
            orderListsOutput.setStatus(order.getStatus() == 1 ? "成功" : "失败");
            orderListsOutputs.add(orderListsOutput);
        }
        return orderListsOutputs;
    }

    @Override
    public Map<String, Object> getOrderInfo(Integer orderId, HttpServletRequest request, HttpServletResponse response) {

        Orders orders = ordersMapper.selectById(orderId);
        if (orders == null) {
            throw new CmsException(401, "错误订单号");
        }
        if (orders.getStatus() == 0) {
            throw new CmsException(402, "订单排队中...");
        } else if (orders.getStatus() == 2) {
            throw new CmsException(403, "订单未成功抢到宿舍");
        }
        HashMap<String, Object> stringObjectHashMap = new HashMap<>();
        stringObjectHashMap.put("status", orders.getStatus());
        stringObjectHashMap.put("room_id", orders.getRoomId());
        return stringObjectHashMap;
    }
}
